﻿using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text;

namespace TruckScale.Helpers
{
  public class DBHelper
  {
    public static IDbConnection DbConnection()
    {
      Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
      return new MySqlConnection(ConfigurationManager.ConnectionStrings["mysql"].ConnectionString);
    }

    public static Dictionary<string, string> ParseConnectionString(string connectionString)
    {
      // 根据分号拆分连接字符串
      string[] parts = connectionString.Split(';');

      // 创建Dictionary来存储键值对
      Dictionary<string, string> connectionDictionary = new Dictionary<string, string>();

      // 遍历分割后的字符串数组
      foreach (var part in parts)
      {
        // 根据等号拆分键值对
        string[] keyValue = part.Split('=');

        // 确保有两个元素，然后将其添加到Dictionary中
        if (keyValue.Length == 2)
        {
          string key = keyValue[0].Trim();
          string value = keyValue[1].Trim();
          connectionDictionary[key] = value;
        }
      }

      return connectionDictionary;
    }

    public static string BuildConnectionString(Dictionary<string, string> connectionDictionary)
    {
      // 使用StringBuilder来构建连接字符串
      StringBuilder connectionStringBuilder = new StringBuilder();

      // 遍历字典中的键值对
      foreach (var kvp in connectionDictionary)
      {
        // 将键值对拼接成连接字符串的形式
        connectionStringBuilder.Append($"{kvp.Key}={kvp.Value};");
      }

      // 移除末尾的分号
      connectionStringBuilder.Length--;

      return connectionStringBuilder.ToString();
    }

  }
}
